// subPages/business/index/index.js
const app = getApp();
var util =  require('../../../utils/util.js');
var json =  require('../../../data/json.js');
var flag = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    btn:{
      btnTxt: '今日收益',
      src: '/resources/theme/earnings.png',
      imgW: '20'
    },
    current: 0,
    logisticsName: '',
    logisticsNum: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    util.setNavBarTitle(that.getTitle(app.globalData.shopType))
    let orderBtnTxt = ''
    var iconNavList = json.iconNavList2
    for(var i in iconNavList){
      iconNavList[i].isShow = false
    }
    switch (app.globalData.shopType) {
      case '0':
        for(var i in iconNavList){
          switch (iconNavList[i].index) {
            case 2:
            case 4:
            case 5:
            case 6:
              iconNavList[i].isShow = true
              break;
          }
        }
        orderBtnTxt = '立即接单'
        break;
      case '1':
        for(var i in iconNavList){
          switch (iconNavList[i].index) {
            case 1:
            case 2:
            case 5:
            case 6:
              iconNavList[i].isShow = true
              break;
          }
        }
        orderBtnTxt = '立即发货'
        that.getCity()
        break;
      case '2':
        for(var i in iconNavList){
          switch (iconNavList[i].index) {
            case 3:
            case 4:
            case 5:
            case 7:
              iconNavList[i].isShow = true
              break;
          }
        }
        orderBtnTxt = '立即接单'
        break;
      case '3':
        iconNavList = json.iconNavList3
        orderBtnTxt = '立即发货'
        that.getLevel()
        break;
    }
    that.setData({
      iconNavList: iconNavList,
      orderBtnTxt: orderBtnTxt,
      shopType: app.globalData.shopType,
      date: util.setTime(new Date()),
    })
    
  },

  getLevel:function(){
    util.getAjax(`${app.globalData.apiUrl}/Api/Alladmin/community_level`,function(res){
      console.log(res)
      if(res.data){
        app.globalData.mainType = res.data.type
        app.globalData.shopUserId = res.data.user_id
      }
    },{id: app.globalData.shopId})
  },

  //获取收益url
  getEarningsUrl:function(shopType){
    var that = this
    var day_sy = ''
    var all_sy = ''
    var data1 = {},data2 = {}
    switch (app.globalData.shopType) {
      case '0':
        day_sy = '/admin_community_service_shop_get_day_sy'
        all_sy = '/admin_community_service_shop_get_all_sy'
        data1 = {service_shop_id: app.globalData.shopId,date: that.data.date}
        data2 = {service_shop_id: app.globalData.shopId}
        break;
      case '1':
        day_sy = '/admin_get_health_shop_day_sy'
        all_sy = '/admin_get_all_sy'
        data1 = {health_shop_id: app.globalData.shopId,date: that.data.date}
        data2 = {health_shop_id: app.globalData.shopId}
        break;
      case '2':
        day_sy = '/admin_community_service_kitchen_get_day_sy'
        all_sy = '/admin_community_service_kitchen_get_all_sy'
        data1 = {kitchen_id: app.globalData.shopId,date: that.data.date}
        data2 = {kitchen_id: app.globalData.shopId}
        break;
      case '3':
        day_sy = '/admin_community_get_day_sy'
        all_sy = '/admin_community_get_all_sy'
        data1 = {community_id: app.globalData.shopId,date: that.data.date}
        data2 = {community_id: app.globalData.shopId}
        break;
    }
    that.getEarningsData(data1,data2,day_sy,all_sy)
  },

  //获取收益
  getEarningsData:function(data1,data2,day_sy,all_sy){
    var that = this
    util.getAjax(`${app.globalData.apiUrl}${day_sy}`,function(res){
      console.log(res)
      that.setData({
        earningToday: res.data?res.data:0
      })
    },data1)
    util.getAjax(`${app.globalData.apiUrl}${all_sy}`,function(res){
      console.log(res)
      that.setData({
        earning: res.data?res.data:0
      })
    },data2)
  },

  //获取城市
  getCity:function(){
    util.getAjax(`${app.globalData.apiUrl}/admin_get_community_health_shop_content`,function(res){
      if(res.data.shi){
        app.globalData.city = res.data.shi
      }
    },{id: app.globalData.shopId})
  },

  //获取评论数量
  getTellNum:function(){
    var that = this
    util.getAjax(`${app.globalData.apiUrl}/shop_get_no_tell`,function(res){
      // console.log(res)
      var iconNavList = json.iconNavList2
      if(res.data && res.data != '0'){
        iconNavList[0].isRound = true
      }else{
        iconNavList[0].isRound = false
      }
      that.setData({
        iconNavList: iconNavList
      })
    },{shop_id: app.globalData.shopId})
  },

  //获取标题
  getTitle:function(type){
    var title = ''
    switch (type) {
      case '0':
        title = '社区商城后台'
        break;
      case '1':
        title = '健康商城后台'
        break;
      case '2':
        title = '特膳厨房后台'
        break;
      case '3':
        title = '加盟商后台'
        break;
    }
    return title
  },

  //获取最新订单
  getOrderList:function(){
    var that = this
    var url = ''
    var data = {}
    switch (app.globalData.shopType) {
      case '0':
        url = '/admin_community_service_shop_get_five_order'
        data = {shop_id: app.globalData.shopId}
        break;
      case '1':
        url = '/admin_get_five_order'
        data = {shop_id: app.globalData.shopId}        
        break;
      case '2':
        url = '/admin_community_service_kitchen_get_five_order'
        data = {kitchen_id: app.globalData.shopId}        
        break;
      case '3':
        url = '/admin_community_get_five_order'
        data = {community_id: app.globalData.shopId}        
        break;
    }
    util.getAjax(`${app.globalData.apiUrl}${url}`,function(res){
      console.log(res)
      if(res.data.length != 0){
        for(var i in res.data){
          var data = [
            {
              text : '收货地址',
              data : res.data[i].address
            },
            {
              text : '姓名',
              data : res.data[i].name
            },
            {
              text : '电话',
              data : res.data[i].phone
            },
            {
              text : '下单时间',
              data : that.data.shopType!='3'?util.setTime2(res.data[i].createtime):util.setTime2(res.data[i].time)
            },
            {
              text : '订单编号',
              data : res.data[i].order_num
            },
            {
              text : '物流状态',
              data : util.getOrderStatus(res.data[i].status)
            },
          ]
          res.data[i].orderList = data
        }
        that.setData({
          isData: true,
          orderList: res.data
        })
        that.getOrderHeight(`.orderAre${that.data.current}`,(rects)=>{
          // console.log(rects)
          that.setData({
            swiperOrderHeight:rects[0].height
          })
        })

      }else{
        that.setData({
          isData: false
        })
      }
    },data)
  },

  //获取订单高度
  getOrderHeight: function (className, callback){
    wx.createSelectorQuery().selectAll(className).boundingClientRect(callback).exec()
  },

  //导航按钮
  iconNavBtn:function(e){
    // console.log(e)
    var index = e.currentTarget.dataset.index
    if(this.data.shopType != 3){
      switch (index+1) {
        case 1:
          wx.navigateTo({
            url: '../evaluation/evaluation?type=' + 1,
          })
          break;
        case 2:
        case 3:
          wx.navigateTo({
            url: '../goods/goods',
          })
          break;
        case 4:
          wx.navigateTo({
            url: '../class/class',
          })
          break;
        case 5:
          wx.navigateTo({
            url: '../earnings/earnings',
          })
          break;
        case 6:
        case 7:
          wx.navigateTo({
            url: '../shop/shop',
          })
          break;
      }
    }else{
      switch (index+1) {
        case 1:
          wx.navigateTo({
            url: '../class/class',
          })
          break;
        case 2:
          wx.navigateTo({
            url: '../goods/goods?type=' + 1,
          })
          break;
        case 3:
          wx.navigateTo({
            url: '../goods/goods?type=' + 2,
          })
          break;
        case 4:
          wx.navigateTo({
            url: '../earnings/earnings',
          })
          break;
      }
    }
    
  },

  swiperOrderChange:function(e){
    var that = this
    var cur = e.detail.current
    if (that.data.current == cur) {
      return
    }else{
      that.setData({
        current: e.detail.current
      })
      that.getOrderHeight(`.orderAre${that.data.current}`,(rects)=>{
        that.setData({
          swiperOrderHeight:rects[that.data.current].height
        })
      })
    }
  },

  //发货按钮
  clickBtn:function(e){
    var that = this
    var id = e.currentTarget.dataset.id
    var urlType = ''
    var data = {}
    switch (that.data.shopType) {
      case '0':
        util.showModelAll('提示','是否确定立即接单',function(){
          urlType = '/service_shop_fahuo';
          util.postAjax(`${app.globalData.apiUrl}${urlType}`,function(res){
            console.log(res)
            if(res.data == 1){
              util.showToast('接单成功','success',2000)
              that.getOrderList()
            }else{
              util.showToast('接单失败，请重新点击','none',2000)
            }
          },{order_id: id})
        })
        break;
      case '1':
        that.setData({
          orderId: id
        })
        var status = e.currentTarget.dataset.status
        that.deliveryAnim(status);
        break;
      case '2':
        util.showModelAll('提示','是否确定立即接单',function(){
          urlType = '/kitchen_shop_fahuo';
          util.postAjax(`${app.globalData.apiUrl}${urlType}`,function(res){
            console.log(res)
            if(res.data == 1){
              util.showToast('接单成功','success',2000)
              that.getOrderList()
            }else{
              util.showToast('接单失败，请重新点击','none',2000)
            }
          },{order_id: id})
        })
        break;
      case '3':
        that.setData({
          orderId: id
        })
        var status = e.currentTarget.dataset.status
        that.deliveryAnim(status);
        break;
    }
  },

  //获取物流公司
  logisticsNameInput:function(e){
    this.setData({
      logisticsName: e.detail.value
    })
  },

  //获取物流单号
  logisticsNumInput:function(e){
    this.setData({
      logisticsNum: e.detail.value
    })
  },

  //完成按钮
  OkDeliveryBtn:function(e){
    var that = this
    if(flag){
      return
    }
    flag = true
    if(!that.data.logisticsName || !that.data.logisticsNum){
      util.showToast('请填写完整物流信息','none',2000)
      flag = false
      return;
    }
    if(that.data.orderId){
      var urlType = ''
      var data = {}
      switch (that.data.shopType) {
        case '1':
          urlType = '/health_shop_up_order';
          data = {order_id: that.data.orderId,address_order_shop: that.data.logisticsName,address_order_num: that.data.logisticsNum}
          break;
        case '3':
          urlType = '/operation_community_jf_shop_order';
          data = {id: that.data.orderId,type: 1,address_order_shop: that.data.logisticsName,address_order_num: that.data.logisticsNum}
          break;
      }
      util.postAjax(`${app.globalData.apiUrl}${urlType}`,function(res){
        console.log(res)
        if(res.data == 1){
          util.showToast('发货成功','success',2000)
          var currentStatus = 'complete';
          that.deliveryAnim(currentStatus);
          that.getOrderList()
          flag = false
        }else{
          util.showToast('发货失败，请重新点击','none',2000)
          flag = false
        }
      },data)
    }
  },
  
  //关闭按钮
  closeBtn:function(){
    var currentStatus = 'complete';
    this.deliveryAnim(currentStatus);
  },

  //动画部分
  deliveryAnim: function (currentStatus) {
    // 第1步：创建动画实例
    var animation = wx.createAnimation({
      duration: 200,  //动画时长
      timingFunction: "linear", //线性
      delay: 0  //0则不延迟
    });

    // 第2步：这个动画实例赋给当前的动画实例
    this.animation = animation;

    // 第3步：执行第一组动画：Y轴偏移240px后(盒子高度是400px)，停
    animation.translateY(350).step();

    // 第4步：导出动画对象赋给数据对象储存
    this.setData({
      deliveryAnim: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画
    setTimeout(function () {
      // 执行第二组动画：Y轴不偏移，停
      animation.translateY(0).step()
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
      this.setData({
        deliveryAnim: animation
      })

      //完成
      if (currentStatus == "complete") {
        this.setData(
          {
            isDelivery: false,
            orderId: '',
            logisticsName: '',
            logisticsNum: '',
          }
        );
      }
    }.bind(this), 200)

    // 显示抽屉
    if (currentStatus == "open") {
      this.setData(
        {
          isDelivery: true,
        }
      );
    }
  },

  //全部订单
  orderBtn:function(){
    wx.navigateTo({
      url: '../orders/orders'
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    that.getEarningsUrl()
    that.getOrderList()
    if(app.globalData.shopType == '1'){
      that.getTellNum()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this
    that.getEarningsUrl()
    that.getOrderList()
    if(app.globalData.shopType == '1'){
      that.getTellNum()
    }
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})